package com.dsx.test.interceptor;


import com.dsx.test.properties.JwtProperties;
import com.dsx.test.shiro.CustomizedToken;
import com.dsx.test.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : tianwenqing
 * @version : 1.0
 * @date : 2020-11-16 17:35
 * @description : shiro 认证拦截器
 **/
@Slf4j
@Component
public class ShiroAuthenticationInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        // 获取请求头信息
        // 如果请求头信息为空则抛出自定义异常
        // 使用jwt去解密 ,然后通过shiro登录
        //返回true通过，返回false拦截
        try {
            String authorization = request.getHeader(JwtProperties.HEADER_TOKEN_NAME);
            if(StringUtils.isBlank(authorization)){

            }
            String userId = JwtUtil.getValueByName(authorization, JwtProperties.USER_ID);

            // 判断jwt中解析属性不能为空
            if(StringUtils.isBlank(userId)){

            }

            CustomizedToken customizedToken = new CustomizedToken(userId, authorization);

            SecurityUtils.getSubject().login(customizedToken);
            return true ;
        } catch (AuthenticationException e) {
            log.info("AuthenticationException" ,e);
            return false;
        }

    }
}
